package com.swing.gui.component.popups;

import base.JPopupMenuBase;
import com.swing.gui.APP;
import com.swing.gui.component.MiniPopup;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import static javax.swing.JOptionPane.WARNING_MESSAGE;
import static javax.swing.JOptionPane.YES_NO_OPTION;

/**
 * @author Yuang, Gongming
 * @date 2022-01-24 11:31
 */
public class UnLockMenu extends JPopupMenu implements JPopupMenuBase {

    private static UnLockMenu unLockMenu;

    private static JMenuItem unlock, exit;

    private UnLockMenu(){}

    public static UnLockMenu init() {
        if (unLockMenu == null) {
            synchronized (UnLockMenu.class) {
                if (unLockMenu == null) {
                    unLockMenu = new UnLockMenu();
                    try {
                        unLockMenu.instance();
                        unLockMenu.style();
                        unLockMenu.listener();
                        unLockMenu.loading();
                    } catch (Exception e) {
                        throw new RuntimeException(UnLockMenu.class.getSimpleName() + " initialization failed");
                    }

                }
            }
        }
        return unLockMenu;
    }

    @Override
    public void instance() {
        unlock = new JMenuItem("解锁");
        exit = new JMenuItem("退出");
    }

    @Override
    public void style() {
        unlock.setBackground(Color.WHITE);
        exit.setBackground(Color.WHITE);

    }

    @Override
    public void listener() {
        unlock.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MiniPopup.jPopupMenu = LockMenu.init();
            }
        });

        exit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                APP.init().setVisible(true);
                APP.init().setExtendedState(JFrame.NORMAL);
                APP.init().toFront();

                if (JOptionPane.showConfirmDialog(APP.init(),
                        "窗口处于锁定状态，可能存在您还未处理的事情，你确定退出？",
                        "窗口锁定",
                        YES_NO_OPTION,
                        WARNING_MESSAGE) == 0) {
                    System.exit(0);
                } else {
                    APP.init().setVisible(APP.init().isVisible());
                }
            }
        });
    }

    @Override
    public void loading() {
        unLockMenu.add(unlock);
        unLockMenu.add(exit);
    }

}
